import mock from "../mock/index.js"
const baseURL = "https://www.imovietrailer.com";
const service = function(config) {
	return new Promise((resolve, reject) => {
		// 请求返回成功的方法
		const success = res => {
			if (res.statusCode == 200) {
				resolve(res.data)
			} else {
				reject(res)
			}
		};
		// http请求失败回调
		const fail = res => {
			let errMsg = "";
			switch (res.statusCode) {
				case 400:
					errMsg = '请求错误';
					break;
				case 401:
					errMsg = '未授权，请登录';
					break;
				case 403:
					errMsg = '拒绝访问';
					break;
				case 404:
					errMsg = `请求地址出错: ${config.url}`;
					break;
				case 408:
					errMsg = '请求超时';
					break;
				case 500:
					errMsg = '服务器内部错误';
					break;
				case 501:
					errMsg = '服务未实现';
					break;
				case 502:
					errMsg = '网关错误';
					break;
				case 503:
					errMsg = '服务不可用';
					break;
				case 504:
					errMsg = '网关超时';
					break;
				case 505:
					errMsg = 'HTTP版本不受支持';
					break;
				default:
			}
			uni.showToast({
				title: errMsg,
				icon: "none"
			});
			console.error(errMsg);
			reject(errMsg);
		};
		// 网络请求
		const toRequest = () => {
			config.url = baseURL + config.url;
			config.success = success;
			config.fail = fail;
			uni.request(config);
		};
		// 是否开启mock
		const openMock = true;
		if (!openMock) {
			toRequest();
		} else {
			mock.response(config).then(mockRes => {
				success(mockRes)
			}).catch(err => {
				toRequest();
			})
		}
	})
}

export default service;
